define(["jquery","ztree","bbcare","fu/app/comm/comm",
	"scprit/nutrition/app/foodLibrary/editFood.servers.js",
    "scprit/nutrition/app/foodLibrary/editFood.ui.js"],
    function($,$ztree,$bb,$comm,$servers,$ui){
	var event = {};

	/**
	 * 删除食物库成功后的回调函数
	 */
	var ajaxFoodlibraryDelCallBack = function(data){
		$bb.openPage("foodLibrary");
	}

	/**
	 * 请求删除食物库
	 */
	var delFoodlibrary = function(){
		var foodLibraryId = $("#foodLibirayTab select").val();
		$servers.ajaxFoodlibraryDel(foodLibraryId,ajaxFoodlibraryDelCallBack);
	}
	/**
	 * 删除食物库
	 */
	var onDelFoodlibrary = function(){
		$bb.toastConfirmShow(delFoodlibrary,null,"您确定要删除该食物库吗？");
	}

	/**
	 * 保存（分类的添加、重命名）成功后的回调函数
	 */
	var ajaxFoodTypeModifyCallBack = function(data,className,foodLibraryId){
		$("." + className).modal("hide");
		onFoodLibraryChange(foodLibraryId,data);
	}

	/**
	 * 保存（分类的添加、重命名）
	 */
	var onSaveFoodClassify = function(){
		var data = $(this).data("params");
		var className = $(this).data("className");
		var foodLibraryId = $("#foodLibirayTab select").val();
		var name = $(this).parents("form").find("input[name=name]").val();
		var remark = $(this).parents("form").find("input[name=remark]").val();
		var params = {
		    "foodTypeName":name,
		    "foodLibraryId":foodLibraryId,
		    "parentId":data.pId,
		    "foodTypeId":data.id
		};
		// 为了防止修改时（不修remark时），把之前填的替换掉
		if(remark && remark != "") $.extend(params,{"remark":remark});
		$servers.ajaxFoodTypeModify(params,ajaxFoodTypeModifyCallBack,className);
	};

	/**
	 * 点击添加、重命名按钮（分类的添加、重命名）
	 */
	var onModifyFoodClassify = function(){
		var data = $(this).data();
		var tit = data.classify == "1" ? "添加根分类" : data.classify == "2" ? "添加子分类" : "重命名";
		var originalName = data.classify == "3" ? data.name : "";
		$("#context-menu").removeClass("open");
		var className = "addNodeModal";
		$comm.modal({
			"className":className,
			"tit":tit
		},function(){
			$ui.modifyFoodClassifyFormInit({
				"dom":$("." + className + " .modal-body"),
				"name":originalName
			});
			$("." + className).modal("show");
			$("#modifyFoodClassifyBtn").unbind("click");
			$("#modifyFoodClassifyBtn").data({"params":data,"className":className});
			$("#modifyFoodClassifyBtn").click(onSaveFoodClassify);
		});
	};

	/**
	 * 删除（分类）
	 */
	var onRemoveFoodClassify = function(){
		$("#context-menu").removeClass("open");
		var data = $(this).data();
		var foodLibraryId = $("#foodLibirayTab select").val();
		var params = {
			"foodTypeId":data.id
		};
		$servers.ajaxFoodTypeDel(params,function(data){
			$bb.toastShow("删除成功！");
			onFoodLibraryChange(foodLibraryId);
		});
	}

	/**
	 * 删除食物
	 */
	var onRemoveFood = function(){
		$("#context-menu").removeClass("open");
		var libraryId = $("#foodLibirayTab select").val();
		var foodId = $(this).data("refId");
		var ajaxFoodDelCallBack = function(data){
			$bb.toastShow("删除成功！");
			onFoodLibraryChange(libraryId);
		};
		var params = {
			"foodId":foodId,
			"callBack":ajaxFoodDelCallBack
		};
		$bb.toastConfirmShow($servers.ajaxFoodDel,params,"您确定删除该食物吗？");
	}

	/**
	 * 保存食物成功后的回调函数
	 */
	var foodModifyCallBack = function(data){
		var foodLibraryId = $("#foodLibirayTab select").val();
		onFoodLibraryChange(foodLibraryId,data);
	}

	/**
	 * 保存食物
	 */
	var onSaveFood = function(){
		var params = $servers.getSaveFoodParams();
		$servers.ajaxFoodModify(params,foodModifyCallBack);
	};

	/**
	 * 添加营养元素成功后的回调函数
	 */
	//给能量 加上单位：
	var addUnitFn = function(data){
		for(var i = 0;i < data.length ; i++){
			if(data[i].nutrientsCode == "ENERC-J" || data[i].nutrientsCode == "ENERC-K"){//能量为kj/kcal时候加上此单位；
				var  unit = data[i].nutrientsUnit;
				if(data[i].nutrientsName.indexOf(unit) == -1){
					data[i].nutrientsName = data[i].nutrientsName+"("+ unit +")";
				}
			}
		}
	};
	//确定添加：
	var sureAddNutrientFn = function(){
		var addArr = [];
		$("#addNutrient_show").find('input[name="check_nutrient"]:checked').each(function(){
			if(!$(this).attr("disabled")){
				addArr.push({
					"nutrientsName":$(this).val(),
					"nutrientsId":$(this).attr("nutrientsId"),
					"nutrientsCode":$(this).attr("nutrientsCode"),
					"nutrientsUnit":$(this).attr("nutrientsUnit")
				});
			}
		});
		for(var i = 0 ;i < addArr.length ; i++){
			var html = '<tr class="new-add-tr" nutrientsCode="'+addArr[i].nutrientsCode+'" nutrientsId="'+addArr[i].nutrientsId+'" >'+
							'<td>'+addArr[i].nutrientsName+'<i class="fa fa-minus del-nutrient"></i></td>'+
							'<td><input type="number"><span>'+addArr[i].nutrientsUnit+'</span></td>'+
						'</tr>';
			$("#nutrientTable tbody").append(html);
		}
		$("#addNutrientBtn").removeAttr("show");
		$(".addNutrient_show").removeClass("show");
	};
	//全选/取消选择：
	var checkAllFn = function(){
		if($(this).html() == '全选'){
			$("#addNutrient_show").find('input[name="check_nutrient"]').each(function(){
				if( !$(this).prop("checked") ){
					$(this).prop("checked",true);
				}
			});
			$(this).html("取消选择");
		}else{
			$("#addNutrient_show").find('input[name="check_nutrient"]').each(function(){
				if( !$(this).attr("disabled") && $(this).prop("checked") ){
					$(this).prop("checked",false);
				}
			});
			$(this).html("全选");
		}
	};
	var ajaxNutrientDictCallBack = function(data){
		addUnitFn(data);
		//遍历列表中已经添加的：
		var nutrientsIdArr = [];
		$("#nutrientTable tbody tr").each(function(){
			nutrientsIdArr.push($(this).attr("nutrientsId"));
		});
		for(var i = 0;i < data.length ; i++){
			if($.inArray(data[i].nutrientsId,nutrientsIdArr) >= 0){
				data[i].flag = true;
			}
		}
		$ui.nutrientListInit2({
			"id":"#addNutrient_show",
			"list":data
		});
		$("#sureAddNutrient").unbind("click");
		$("#sureAddNutrient").click(sureAddNutrientFn);
		//全选：
		$("#checkAll").unbind("click");
		$("#checkAll").click(checkAllFn);

		$("#nutrientTable tbody").off("click","tr td i.del-nutrient");
		$("#nutrientTable tbody").on("click","tr td i.del-nutrient",function(){
			$(this).parents("tr.new-add-tr").remove();
		});
	}
	/**
	 * 添加营养元素
	 */
	var onAddNutrient = function(){
		if($("#addNutrientBtn").attr("show")){
			$servers.ajaxNutrientDict(ajaxNutrientDictCallBack);
		}
	}

	/**
	 * 查询食物基本详情成功后的回调函数 (修改食物、添加食物)
	 */
	var ajaxFoodDetailCallBack = function(data){
		var tit;
		if(data){
			if(data.id){
				tit = "添加食物";
				data.foodTypeId = data.id;
				data.foodTypeName = data.name;
			}else{
				tit = "修改食物";
			}
		}else{
			data = {};
			tit = "添加食物";
		}
		$ui.editFoodBoxInit({
			"id":"editFoodBox",
			"tit":tit,
			"data":data
		});
		$("#addNutrientBtn").click(function(){
			if($(this).attr("show")){
				$(".addNutrient_show").removeClass("show");
				$(this).removeAttr("show");
			}else{
				$(".addNutrient_show").addClass("show");
				$(this).attr("show",true);
			}
		});
		//$("#addNutrientBtn").unbind('click');
		$("#addNutrientBtn").click(onAddNutrient);
		$("#nutrientTable tbody tr td i.del-nutrient").click(function(){
			$(this).parents("tr.original-tr").remove();
		});
		var topbars = [
            {
                "icon":"fa fa-floppy-o",
                "name":"保存",
                "callback":onSaveFood
            },
            {
            	"icon":"fa fa-times",
                "name":"删除",
                "callback":onDelFoodlibrary
            }
        ];
        $bb.toolbar(topbars);
        $("#saveNutrientBtn").click(onSaveFood);
	}

	/**
	 * 右键：右键菜单的样式，定位，显示
	 */
	var menuRightClick = function(event,flag){
		var mouseX = event.originalEvent.x || event.originalEvent.layerX || 0; 
		var mouseY = event.originalEvent.y || event.originalEvent.layerY || 0;
		// 疗程分类右键菜单：foodClassify; 疗程右键菜单：food; 空白处：blank
		$ui.contextMenu({
			"id":"context-menu",
			"flag":flag
		});
		$("#context-menu").css({
			"position": "absolute",
		    "zIndex": 9999,
		    "top": mouseY + 'px',
		    "left": mouseX + 'px',
		}).addClass("open");
		$(document).click(function(){
			$("#context-menu").removeClass("open");
		});
		$("#context-menu").click(function(event){
			event.stopPropagation();
		});
	}

	var $ztree = {
		// 禁止拖拽
		beforeDrag: function(treeId,treeNodes){
			return false;
		},
		// 右键疗程不出现菜单
		beforeRightClick: function(treeId,treeNode){
			return true;
		},
		onRightClick: function(event,treeId,treeNode){
			if(treeNode != null){
				if(treeNode.isLeaf == "1"){
					menuRightClick(event,"food"); // food 疗程的右键菜单
					// 删除（食物）
					$("#context-menu .remove").unbind("click");
					$("#context-menu .remove").data({"refId":treeNode.refId});
					$("#context-menu .remove").click(onRemoveFood);
				}else{
					menuRightClick(event,"foodClassify"); // foodClassify 疗程分类的右键菜单
					// 重命名（分类的重命名）
					$("#context-menu .rename").unbind("click");
					$("#context-menu .rename").data({"classify":"3","pId":treeNode.pId,"id":treeNode.id,"name":treeNode.name});
					$("#context-menu .rename").click(onModifyFoodClassify);
					// 添加根分类
					$("#context-menu .addRootClassify").unbind("click");
					$("#context-menu .addRootClassify").data({"classify":"1","pId":treeNode.pId});
					$("#context-menu .addRootClassify").click(onModifyFoodClassify);
					// 添加子分类
					$("#context-menu .addSubClassify").unbind("click");
					$("#context-menu .addSubClassify").data({"classify":"2","pId":treeNode.id});
					$("#context-menu .addSubClassify").click(onModifyFoodClassify);
					// 删除（分类）
					$("#context-menu .remove").unbind("click");
					$("#context-menu .remove").data({"id":treeNode.id});
					$("#context-menu .remove").click(onRemoveFoodClassify);
				}
			}
		},
		beforeClick: function(treeId,treeNode,clickFlag){
			return true;
		},
		onClick: function(event,treeId,treeNode){
			if(treeNode && treeNode.isLeaf && treeNode.isLeaf == "1"){ // 修改食物
				$servers.ajaxFoodDetail(treeNode.refId,ajaxFoodDetailCallBack);
			}else{ // 添加食物
				ajaxFoodDetailCallBack(treeNode);
			}
		}
	}

	/**
	 * 查询食物库下食物树形菜单成功后的回调函数
	 */
	var ajaxFoodMenusCallBack = function(data,req){
		$ui.foodMenusInit({
			"id":"ztreeFoodLibirayWrap",
			"list":data
		});
		if(data.length == 0){
			// 点击疗程库空白处 添加分类、疗程节点
	        $('#ztreeFoodLibirayWrap').contextmenu(function(){
	        	return false;
	        });
	        $("#ztreeFoodLibirayWrap").mousedown(function(event) {
	            if (3 == event.which) {   //右键为3
	                menuRightClick(event,"blank"); // course 疗程的右键菜单
	                // 添加根分类
					$("#context-menu .addRootClassify").unbind("click");
					$("#context-menu .addRootClassify").data({"classify":"1"});
					$("#context-menu .addRootClassify").click(onModifyFoodClassify);
	            } 
	        });
	        ajaxFoodDetailCallBack(null);
		}else{
			var setting = {
		    	view: {
					selectedMulti: false,
				},
				edit: {
					enable: true,
					showRemoveBtn: false,
					showRenameBtn: false,
				},
		    	data: {
		    		keep: {
						leaf: true,
						parent: true
					},
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeDrag: $ztree.beforeDrag,
					beforeRightClick: $ztree.beforeRightClick,
					onRightClick: $ztree.onRightClick,
					beforeClick: $ztree.beforeClick,
					onClick: $ztree.onClick
				}
		    };
		    var treeObj = $.fn.zTree.init($("#ztreeFoodLibiray"),setting,data);
		    treeObj.expandAll(false); // 全展开
		    // 没有传参数时，左边显示数据里的第一个，传的是foodTypeId时，显示新增，传的是foodId，显示修改
		    var nodeId = req ? req.foodId ? $servers.getNodeId(req.foodId,data) : req.foodTypeId : data[0].id;
		    var node = treeObj.getNodeByParam('id', nodeId );
	        treeObj.selectNode(node);//选择点  
	        treeObj.setting.callback.onClick(null,treeObj.setting.treeId,node);//调用事件
		}
	}

	/**
	 * 选择食品库
	 */
	var onFoodLibraryChange = function(libraryId,data){
        $servers.ajaxFoodMenus(libraryId,ajaxFoodMenusCallBack,data);
	}
	event.onfoodLibirayChange = function(){
		var libraryId = $(this).val();
        onFoodLibraryChange(libraryId);
	}

	return event;
});